package com.houdoudou.supplier.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.supplier.R;
import com.houdoudou.supplier.SupplierMainActivity;
import com.houdoudou.supplier.bean.Product;
import com.houdoudou.supplier.bean.Supplier;
import com.houdoudou.supplier.common.CommonFunction;
import com.houdoudou.supplier.common.Constant;
import com.houdoudou.supplier.fragment.ProductBasicFragment.MyListAdapter.Zujian;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class ProductAllFragment extends Fragment{

	TextView result;
	View.OnClickListener myOnclickListener;

	Button confirm;
	ProgressBar progres;
	ListView listview_product,listview_branch;
	ProductListAdapter myProductListAdapter;
	JSONArray productsJA= new JSONArray();
    String affair="";
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 View view =inflater.inflate(R.layout.frg_product_all, container, false);
           init_listener();
           init_component(view);
		    confirm.performClick();
		 return view;
	}

	@Override
	public void setArguments(Bundle bundle) {
		// TODO Auto-generated method stub
		// super.setArguments(args);
		affair=bundle.getString("affair");
		if(affair.equals("updateProduct")){
		
		}
	}
  
	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		if(!hidden){	
			assign();
		}
	}
	
	private void assign(){
		System.out.println("affair="+affair);
		
	} 
	private void init_listener(){
		
		
		myOnclickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				 result.setText("请稍后");
				    progres.setVisibility(View.VISIBLE);
					confirm.setEnabled(false);
				String[] params= new String[3];
   	            params[0]=Constant.BaseUrl+Constant.SupplierUrl;
                params[1]="searchProduct"; //PostCode
				JSONObject product= new JSONObject();
				product.put(Product.SUPPLIER, Constant.supplierJO.get(Supplier.TELNUM));
	              params[2]=product.toString();
	              new HttpPostTaskforProductALL().execute(params);
				
				
			}
		};		
	}
	
	
	private void init_component(View view){
		
	
		confirm=(Button) view.findViewById(R.id.btn_confirm_frg_product_all);
	
		result=(TextView) view.findViewById(R.id.tv_functionresult_frg_product_all);
		progres= (ProgressBar) view.findViewById(R.id.prgs_frg_product_all);
		listview_product= (ListView) view.findViewById(R.id.listView_frg_product_all);
		
		//////////////////////
		
		confirm.setOnClickListener(myOnclickListener);
	
		progres.setVisibility(View.INVISIBLE);
		
		myProductListAdapter= new ProductListAdapter(getActivity());
		listview_product.setAdapter(myProductListAdapter);
		
		
	
		
	}
	
	
	
	
	
	private  class HttpPostTaskforProductALL extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			  Map<String,Object> map =	CommonFunction.UniversalHttpPost(params);		             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
			// TODO Auto-generated method stub
		  //	super.onPostExecute(result);
			confirm.setEnabled(true);
			result.setText("");
			 progres.setVisibility(View.INVISIBLE);
			 String PostResult=(String) map.get("PostResult");
			 String affairOnline="";
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				  result.setText("提示:网络故障或者网络配置有误，无法连接到服务器");
			      return;
			}
				Toast.makeText( getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean ActionStatus=false;
				String ErrorInfo="";
				JSONObject json = null;
				try{
			     json= JSONObject.fromObject(PostResult);
				 ActionStatus=json.getBoolean("success");
				 ErrorInfo=json.getString("errorInfo");	
				 affairOnline= json.getString("affair");
				}catch(JSONException e){
					
					result.setText("提示:JSON解析错误");
					 return;
				}
				 result.setText("提示:"+ErrorInfo);
				 if(!ActionStatus){ return;  }  
				 if(affairOnline.equals("searchProduct")){										   												      		              
		    	   productsJA= json.getJSONArray("products");			
					 myProductListAdapter.notifyDataSetChanged();   
		             } 	
		                 	
           
				 if(affairOnline.equals("deleteProduct")){	
					 int deletedID= json.getJSONObject("product").getInt(Product.ID);
					 for(int i=0;i<productsJA.size();i++){
						 if(productsJA.getJSONObject(i).getInt(Product.ID)==deletedID){
							    productsJA.remove(i);
							    myProductListAdapter.notifyDataSetChanged();   
							    return; }	 }         			            	
     	                 }				
		  		
		
			
			
		} //onPostExecute
 } //AsyncTask
	
	class ProductListAdapter extends BaseAdapter {
		   
		    private LayoutInflater layoutInflater;  
		    private Context context;  
		    
		public ProductListAdapter(Context context) {
				super();
					
				this.context = context;
			    this.layoutInflater=LayoutInflater.from(context); 
			}
		
		
		final class Zujian{  
		    public TextView id,name,sale,sort,isauth,type;  
	        public Button del,see,modify;
	       
	      
	    
	   }   //end of Zujian

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			 return productsJA.size();  
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			 return productsJA.get(position);  
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position; 
		}
	 
		@Override
		public View getView(int position, View  convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int selectID = position;   
			 Zujian zujian=null;  
		        if(convertView==null){  
		            zujian=new Zujian();  
		            //获得组件，实例化组件  
		            convertView=layoutInflater.inflate(R.layout.list_product_all, null);  
		          
		            zujian.id=(TextView) convertView.findViewById(R.id.tv_id_list_product_all);
		            zujian.name=(TextView) convertView.findViewById(R.id.tv_name_list_product_all); 
		            zujian.sale=(TextView) convertView.findViewById(R.id.tv_salenum_list_product_all); 
		            
		            zujian.sort=(TextView) convertView.findViewById(R.id.tv_index_list_product_all);     
		            zujian.isauth=(TextView) convertView.findViewById(R.id.tv_isauth_list_product_all);   
		            zujian.type=(TextView) convertView.findViewById(R.id.tv_type_list_product_all);   
		            zujian.del= (Button) convertView.findViewById(R.id.btn_del_list_product_all);
		            zujian.modify= (Button) convertView.findViewById(R.id.btn_modify_list_product_all);
		            zujian.see= (Button) convertView.findViewById(R.id.btn_see_list_product_all);
		            convertView.setTag(zujian);  
		            System.out.println("position----"+position+"------inflated");
		        }else{   System.out.println("position----"+position+"-------not inflated");
		            zujian=(Zujian)convertView.getTag();  
		        }  
		        //绑定数据  
		        zujian.id.setText( productsJA.getJSONObject(selectID).getInt(Product.ID)+"");		       
		        zujian.name.setText(productsJA.getJSONObject(selectID).getString(Product.NAME));
		        zujian.sale.setText(productsJA.getJSONObject(selectID).getInt(Product.SALE)+"");
		        zujian.sort.setText( productsJA.getJSONObject(selectID).getString("sortname"));	        
		       int auth=productsJA.getJSONObject(selectID).getInt(Product.ISAUTH);
		        if(auth==1) { zujian.isauth.setText("上架");
		        	}else if(auth==2){ zujian.isauth.setText("下架"); 
	             	}else if(auth==0){ zujian.isauth.setText("未定义"); }
		        int type=productsJA.getJSONObject(selectID).getInt(Product.TYPE);
		        if(type==2) { zujian.type.setText("易变质产品");
		        	}else if(type==1){ zujian.type.setText("普通产品"); 
		        	}else if(type==0){ zujian.type.setText("未定义"); }
		       
		        zujian.del.setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {
						String[] params= new String[3];
		   	            params[0]=Constant.BaseUrl+Constant.SupplierUrl;
		                params[1]="deleteProduct"; //PostCode
						JSONObject product= new JSONObject();
						product.put(Product.ID, productsJA.getJSONObject(selectID).getInt(Product.ID));
						product.put(Product.DIR, productsJA.getJSONObject(selectID).getString(Product.DIR));
			            params[2]=product.toString();
			            new HttpPostTaskforProductALL().execute(params);
					
					}
				});
		        
		        zujian.see.setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {					
						Message msg = new Message();               
	                   msg.what=2;
	                   msg.arg1=0;
	                   msg.arg2=2;
	                  Bundle bundle= new Bundle(); 
	                  bundle.putString("affair", "seeProduct");
	                  bundle.putString("product", productsJA.getJSONObject(selectID).toString());
	             
	          		bundle.putString("tag", "TAG_SEEPRODUCT"+productsJA.getJSONObject(selectID).getInt(Product.ID));
	          		bundle.putString("title", "查看商品"+productsJA.getJSONObject(selectID).getInt(Product.ID));
	          	
	                  msg.obj=bundle;
	                   SupplierMainActivity.myMainHandler.sendMessage(msg);	
					}
				});
		        zujian.modify.setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {					
						Message msg = new Message();               
	                   msg.what=2;
	                   msg.arg1=0;
	                   msg.arg2=2;
	                  Bundle bundle= new Bundle(); 
	                  bundle.putString("affair", "updateProduct");
	                  bundle.putString("product", productsJA.getJSONObject(selectID).toString());
	                  bundle.putString("tag", "TAG_UPDATEPRODUCT"+productsJA.getJSONObject(selectID).getInt(Product.ID));
		          		bundle.putString("title", "修改商品"+productsJA.getJSONObject(selectID).getInt(Product.ID));
	                  msg.obj=bundle;
	                   SupplierMainActivity.myMainHandler.sendMessage(msg);	
					}
				});
		        return convertView;
	           } 
	      }// end Adapter
			 
	
}
